package com.jiutong.meipengdai.ui.activitys;

import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.entity.LoanDetailBean;
import com.jiutong.meipengdai.entity.MyloanBean;
import com.jiutong.meipengdai.http.model.interfaces.LoanRelaBize;
import com.jiutong.meipengdai.http.model.requests.LoanRelaRequest;
import com.jiutong.meipengdai.http.present.LoanRelaPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.ui.adapter.LoanDetailAdapter;
import com.jiutong.meipengdai.utils.NumUilt;
import com.jiutong.meipengdai.views.dialog.BaseDialog;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 贷款详情
 * Created by suxi on 2017/5/27.
 */

public class LoanDetailActivity extends BaseActivity implements View.OnClickListener, LoanRelaBize {

    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.iv_back)
    ImageView iv_back;
    @Bind(R.id.rl_back)
    RelativeLayout rl_back;
    TextView tv_loan_detail_time;
    TextView tv_loan_total_money;
    TextView tv_total_rate;
    TextView tv_month_rate;
    TextView tv_collateral_house;
    TextView tv_type;
    View top_bg;
    TextView tv_change_loan_check;
    TextView tv_loan_detail_look;
    @Bind(R.id.lv_payment_plan_list)
    ListView lv_payment_plan_list;
    LinearLayout ll_wtg;
    @Bind(R.id.btn_apply_day)
    Button btn_apply_day;
    TextView tv_payment_plan;
    TextView tv_loan_detail_month;
    LinearLayout llZhanqiDesc;
    TextView tvZhanqiGuize; //展期规则
    @Bind(R.id.tv_options)
    TextView tvOptions;
    BaseDialog dialog;
    private LoanDetailAdapter adapter;
    private MyloanBean.DataBean date;
    private TextView tv_check_house;
    private List<LoanDetailBean.DataBean.RepayRecordsBean> repayRcord;
    private String loanId;
    private LoanDetailBean.DataBean.LoanInfoPojoBean loanInfoPojo;
    private String showExtension;
    private List<LoanDetailBean.DataBean.LoanPostponesBean> loanPostpones;
    private LoanRelaRequest request;
    private SubscriberOnNextListener onNextListener;
    private ProgressSubscriber progressSubscriber;
    private HashMap fieldsMap;
    private String houseId;
    private String auditStatus;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_loan_detail;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        View headerView = View.inflate(mContext, R.layout.loan_detail_header, null);
        tv_loan_detail_time = (TextView) headerView.findViewById(R.id.tv_loan_detail_time);
        tv_loan_detail_month = (TextView) headerView.findViewById(R.id.tv_loan_detail_month);
        tv_type = (TextView) headerView.findViewById(R.id.tv_type);
        tv_loan_total_money = (TextView) headerView.findViewById(R.id.tv_loan_total_money);
        tv_month_rate = (TextView) headerView.findViewById(R.id.tv_month_rate);
        tv_total_rate = (TextView) headerView.findViewById(R.id.tv_total_rate);
        tv_collateral_house = (TextView) headerView.findViewById(R.id.tv_collateral_house);
        tv_loan_detail_look = (TextView) headerView.findViewById(R.id.tv_loan_detail_look);
        tvZhanqiGuize = (TextView) headerView.findViewById(R.id.tv_zhanqi_guize);
        top_bg = headerView.findViewById(R.id.top_bg);
        tv_change_loan_check = (TextView) headerView.findViewById(R.id.tv_change_loan_check);
        ll_wtg = (LinearLayout) headerView.findViewById(R.id.ll_wtg);
        llZhanqiDesc = (LinearLayout) headerView.findViewById(R.id.ll_zhanqi_desc);
        tv_payment_plan = (TextView) headerView.findViewById(R.id.tv_payment_plan);


        tv_title.setText("贷款详情");
        tv_check_house = (TextView) findViewById(R.id.tv_loan_detail_look);

        lv_payment_plan_list.addHeaderView(headerView);
    }

    @Override
    protected void initDate(Bundle savedInstanceState) {
        super.initDate(savedInstanceState);
        date = getIntent().getExtras().getParcelable("date");
        loanId = getIntent().getStringExtra("loanId");
        LoanRelaPresent loanRelaPresent = new LoanRelaPresent(mContext, this);
        loanRelaPresent.loanDetail(loanId);

    }

    @Override
    protected void initEvent() {
        super.initEvent();
        rl_back.setOnClickListener(this);
        tv_loan_detail_look.setOnClickListener(this);
        btn_apply_day.setOnClickListener(this);
        tvZhanqiGuize.setOnClickListener(this);
        tvOptions.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back:  //退出
                finish();
                break;
            case R.id.btn_apply_day: //申请展期
                if (dialog == null) {
                    dialog = new BaseDialog.Builder()
                            .layResuorce(R.layout.dailog_apply_day)
                            .okViewClickEvent(R.id.tv_setting_ok)
                            .cancelViewClickEvent(R.id.tv_setting_cancel)
                            .animResource(R.style.dialog_animation_fade)
                            .gravityStyle(Gravity.CENTER)
                            .dialogWidth(-2)
                            .build();
                    dialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                        @Override
                        public void onOkClick() {
                            dialog.dismiss();
                            applyDay();
                        }

                        @Override
                        public void onOk2Click() {

                        }
                    });
                }
                dialog.show(getSupportFragmentManager(), "tag");
                break;
            case R.id.tv_loan_detail_look: //贷款详情
//                Bundle bundle = new Bundle();
//                bundle.putParcelable("data", data);
                Bundle bundle = new Bundle();
                bundle.putString("houseId", houseId);
                openActivity(HouseDetailActivity.class, bundle);
                break;

            case R.id.tv_zhanqi_guize:

                BaseDialog baseDialog = new BaseDialog.Builder().layResuorce(R.layout.dialog_zhanqi_guize)
                        .cancelViewClickEvent(R.id.iv_cancel)
                        .dialogWidth(-1)
                        .animResource(R.style.dialog_animation)
                        .gravityStyle(Gravity.BOTTOM)
                        .build();

                baseDialog.show(getSupportFragmentManager(), TAG);
                break;

            case R.id.tv_options:

                Bundle bundle1 = new Bundle();
                bundle1.putString("loanId", loanId);
                openActivity(RepayPlanActivity.class, bundle1);
                break;
        }
    }

    private void applyDay() {
        if (request == null) {
            request = new LoanRelaRequest();
            onNextListener = new SubscriberOnNextListener<BaseRespond>() {
                @Override
                public void onNext(BaseRespond o) {
                    if (o.getResCode().equals("200")) {
                        toastShortShow("成功发起申请");
                    }
                }

                @Override
                public void onError(Throwable e) {

                }
            };
            fieldsMap = new HashMap();
            fieldsMap.put("loanId", loanId);
            progressSubscriber = new ProgressSubscriber(onNextListener, this);
        }
        request.applyDay(progressSubscriber, fieldsMap);
    }

    @Override
    public String getAreaName() {
        return null;
    }

    @Override
    public String getLocaName() {
        return null;
    }

    @Override
    public String getOrientate() {
        return null;
    }

    @Override
    public String getArea() {
        return null;
    }

    @Override
    public String getInFloor() {
        return null;
    }

    @Override
    public String getTotalFloor() {
        return null;
    }

    @Override
    public String getHouseNum() {
        return null;
    }

    @Override
    public void onSuccess(Object object) {
        LoanDetailBean detailBean = (LoanDetailBean) object;
        repayRcord = detailBean.getData().getRepayRecords();
        loanInfoPojo = detailBean.getData().getLoanInfoPojo();
        showExtension = detailBean.getData().getShowExtension();
        loanPostpones = detailBean.getData().getLoanPostpones();
        tv_loan_detail_month.setText(loanInfoPojo.getLoanDeadline());

        String loanAmount = date.getLoanAmount();
        String finalAssAmount = loanInfoPojo.getFinalAssAmount();
        if (loanPostpones.size() > 0) {
            auditStatus = loanPostpones.get(0).getAuditStatus();

            showApplyDayDialog(auditStatus);
        }
        houseId = loanInfoPojo.getHouseId();


        lv_payment_plan_list.setAdapter(new LoanDetailAdapter(this, repayRcord, R.layout.loan_detail_lsit, loanAmount, finalAssAmount, auditStatus, loanPostpones));
        int ex = Integer.parseInt(showExtension);
        if (ex == 0) {
            btn_apply_day.setVisibility(View.GONE);
        } else if (ex == 1) {
            btn_apply_day.setVisibility(View.VISIBLE);
        }
        tv_loan_detail_time.setText(loanInfoPojo.getApplyDate());
        tv_month_rate.setText(loanInfoPojo.getLoanRate() + "%");
        tv_total_rate.setText(loanInfoPojo.getLoanInterest());


        if (!"null".equals(loanInfoPojo.getLoanAmount()) && Double.parseDouble(loanInfoPojo.getLoanAmount()) >= 10000) {

            tv_loan_total_money.setText(NumUilt.formatDouble(Double.parseDouble(loanInfoPojo.getLoanAmount()) / 10000) + " 万");
        } else {
            tv_loan_total_money.setText(loanInfoPojo.getLoanAmount());
        }

        tv_collateral_house.setText(loanInfoPojo.getHouseCardFull());

        if (!TextUtils.isEmpty(loanInfoPojo.getLoanStatus())) {
            String loanStatus = loanInfoPojo.getLoanStatus();
            int loanStatusNum = Integer.parseInt(loanStatus);
            if (loanStatusNum == 1 || loanStatusNum == 2 || loanStatusNum == 3) {
                tv_type.setText("审核中");
                top_bg.setBackgroundResource(R.color.green);
                tv_type.setTextColor(getResources().getColor(R.color.green));
//                tv_change_loan_check.setText("申请日期");
//                tv_loan_detail_look.setText(loanInfoPojo.getApplyDate());
//                tv_loan_detail_look.setTextColor(getResources().getColor(R.color.defalult_black));
//                lv_payment_plan_list.setVisibility(View.GONE);
            }
            if (loanStatusNum == 5) {
                tv_type.setText("还款中");
                top_bg.setBackgroundResource(R.color.orange);
                tv_type.setTextColor(getResources().getColor(R.color.orange));
//                btn_apply_day.setVisibility(View.VISIBLE);
//                tvOptions.setVisibility(View.VISIBLE);
//                tvOptions.setText("还款计划");
//                tvOptions.setTextColor(getResources().getColor(R.color.default_gray));
                llZhanqiDesc.setVisibility(View.VISIBLE);
            }

            if (loanStatusNum == 6) {
                top_bg.setBackgroundResource(R.color.gray);
                tv_type.setTextColor(getResources().getColor(R.color.gray));
                tv_type.setText("已还清");
                llZhanqiDesc.setVisibility(View.VISIBLE);
            }

            if (loanStatusNum == 4) {
                top_bg.setBackgroundResource(R.color.red);
                tv_type.setTextColor(getResources().getColor(R.color.red));
                tv_type.setText("未通过");
//                lv_payment_plan_list.setVisibility(View.GONE);
                ll_wtg.setVisibility(View.VISIBLE);
            }
        }
    }

    private void showApplyDayDialog(String auditStatus) {
        if (auditStatus.equals("2") && !"6".equals(loanInfoPojo.getLoanStatus())) {
            if (dialog == null) {
                dialog = new BaseDialog.Builder()
                        .layResuorce(R.layout.apply_day_pass)
                        .okViewClickEvent(R.id.tv_setting_cancel)
                        .animResource(R.style.dialog_animation_fade)
                        .gravityStyle(Gravity.CENTER)
                        .dialogWidth(-2)
                        .build();
                dialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                    @Override
                    public void onOkClick() {
                        dialog.dismiss();
                    }

                    @Override
                    public void onOk2Click() {

                    }
                });
            }
            dialog.show(getSupportFragmentManager(), "tag");
        } else if (auditStatus.equals("3") && !"6".equals(loanInfoPojo.getLoanStatus())) {
            if (dialog == null) {
                dialog = new BaseDialog.Builder()
                        .layResuorce(R.layout.apply_day_nopass)
                        .okViewClickEvent(R.id.tv_setting_cancel)
                        .animResource(R.style.dialog_animation_fade)
                        .gravityStyle(Gravity.CENTER)
                        .dialogWidth(-2)
                        .build();
                dialog.setOnDialogClickListener(new BaseDialog.OnDialogClickListener() {
                    @Override
                    public void onOkClick() {
                        dialog.dismiss();
                    }

                    @Override
                    public void onOk2Click() {

                    }
                });
            }
            dialog.show(getSupportFragmentManager(), "tag");
        }

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("LoanDetail Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }
}
